<?php
namespace app\controller\api;

use app\BaseController;
use app\FrontendController;
use think\facade\Request;
use think\facade\Db;
use app\model\frontend\BlindBoxModel;
use app\model\tool\ImageModel;
use app\model\frontend\OrderModel;

/**
 * 盲盒前台API控制器
 * Class BlindBox
 * @package app\controller\api
 */
class BlindBox extends FrontendController
{
    /**
     * 获取盲盒列表（前台展示）
     * @return void
     */
    public function get_list()
    {
        global $_W;
        
        $uniacid = $_W['uniacid'];
        
        $filter = [
            'status' => 1  // 只显示上架的盲盒
        ];
        
        if (!empty($_GET['name'])) {
            $filter['name'] = $_GET['name'];
        }
        
        $list = BlindBoxModel::get_list($uniacid, $filter);
        
        $now = date('Y-m-d H:i:s');
        $result = [];
        
        foreach ($list as $item) {
            // 检查时间范围
            if (!empty($item['start_time']) && $now < $item['start_time']) {
                $item['can_buy'] = false;
                $item['buy_tips'] = '活动未开始';
            } elseif (!empty($item['end_time']) && $now > $item['end_time']) {
                $item['can_buy'] = false;
                $item['buy_tips'] = '活动已结束';
            } elseif ($item['stock'] > 0 && $item['sold'] >= $item['stock']) {
                $item['can_buy'] = false;
                $item['buy_tips'] = '已售罄';
            } else {
                $item['can_buy'] = true;
                $item['buy_tips'] = '';
            }
            
            // 处理图片
            if (!empty($item['image'])) {
                $item['image'] = ImageModel::resize2($item['image'], 300, 300);
            }
            
            // 计算剩余库存
            if ($item['stock'] > 0) {
                $item['remain_stock'] = $item['stock'] - $item['sold'];
            } else {
                $item['remain_stock'] = -1; // 无限库存
            }
            
            $result[] = $item;
        }
        
        echo json_encode($result);
    }

    /**
     * 获取盲盒详情
     * @return void
     */
    public function detail()
    {
        global $_W;
        
        $uniacid = $_W['uniacid'];
        $blind_box_id = $_GET['blind_box_id'];
        
        $res = [
            'status' => 0
        ];
        
        $detail = BlindBoxModel::detail($uniacid, $blind_box_id);
        
        if (empty($detail) || $detail['status'] != 1) {
            $res['status'] = 1;
            $res['description'] = '盲盒不存在或已下架';
            echo json_encode($res);
            return;
        }
        
        // 处理图片
        if (!empty($detail['image'])) {
            $detail['image'] = ImageModel::resize2($detail['image'], 600, 600);
        }
        
        // 获取奖品列表（只显示启用的）
        $prizes = BlindBoxModel::get_prizes($uniacid, $blind_box_id);
        $active_prizes = [];
        
        foreach ($prizes as $prize) {
            if ($prize['status'] == 1) {
                if (!empty($prize['prize_image'])) {
                    $prize['prize_image'] = ImageModel::resize2($prize['prize_image'], 200, 200);
                }
                $active_prizes[] = $prize;
            }
        }
        
        $detail['prizes'] = $active_prizes;
        
        // 检查当前用户购买限制
        if (!empty($_W['customer'])) {
            $customer_id = $_W['customer']['id'];
            $limit_check = BlindBoxModel::check_user_limit($uniacid, $blind_box_id, $customer_id);
            $detail['user_limit'] = $limit_check;
        }
        
        // 检查是否可购买
        $now = date('Y-m-d H:i:s');
        if (!empty($detail['start_time']) && $now < $detail['start_time']) {
            $detail['can_buy'] = false;
            $detail['buy_tips'] = '活动未开始';
        } elseif (!empty($detail['end_time']) && $now > $detail['end_time']) {
            $detail['can_buy'] = false;
            $detail['buy_tips'] = '活动已结束';
        } elseif ($detail['stock'] > 0 && $detail['sold'] >= $detail['stock']) {
            $detail['can_buy'] = false;
            $detail['buy_tips'] = '已售罄';
        } elseif (!empty($detail['user_limit']) && !$detail['user_limit']['can_buy']) {
            $detail['can_buy'] = false;
            $detail['buy_tips'] = '已达到购买上限';
        } else {
            $detail['can_buy'] = true;
            $detail['buy_tips'] = '';
        }
        
        $res['blind_box'] = $detail;
        
        echo json_encode($res);
    }

    /**
     * 抽取盲盒
     * 用于用户主动抽取已购买但未抽奖的盲盒
     * @return void
     */
    public function draw()
    {
        global $_W, $_GPC;
        
        $uniacid = $_W['uniacid'];
        
        $res = [
            'status' => 0
        ];
        
        // 检查登录状态
        if (empty($_W['customer'])) {
            $res['status'] = 1;
            $res['description'] = '请先登录';
            echo json_encode($res);
            return;
        }
        
        $customer_id = $_W['customer']['id'];
        
        // 获取请求参数
        $order_blind_box_id = $_GPC['order_blind_box_id'] ?? null;
        $order_id = $_GPC['order_id'] ?? null;
        $blind_box_id = $_GPC['blind_box_id'] ?? null;
        
        if (empty($order_blind_box_id) && empty($order_id)) {
            $res['status'] = 1;
            $res['description'] = '缺少必要参数';
            echo json_encode($res);
            return;
        }
        
        // 查询未抽奖的盲盒订单记录
        $where = [];
        if ($order_blind_box_id) {
            $where['id'] = $order_blind_box_id;
        } elseif ($order_id) {
            $where['order_id'] = $order_id;
            if ($blind_box_id) {
                $where['blind_box_id'] = $blind_box_id;
            }
        }
        $where['is_drawn'] = 0;
        
        $order_blind_box = BlindBoxModel::get_order_blind_box($uniacid, $where);
        
        if (empty($order_blind_box)) {
            $res['status'] = 1;
            $res['description'] = '没有可抽奖的盲盒订单';
            echo json_encode($res);
            return;
        }
        
        // 验证订单是否属于当前用户
        $order_info = OrderModel::get_single($order_blind_box['order_id']);
        if (empty($order_info) || $order_info['customer_id'] != $customer_id) {
            $res['status'] = 1;
            $res['description'] = '订单不存在或无权限';
            echo json_encode($res);
            return;
        }
        
        // 检查订单是否已支付
        if ($order_info['is_payed'] != 1) {
            $res['status'] = 1;
            $res['description'] = '订单未支付，无法抽奖';
            echo json_encode($res);
            return;
        }
        
        // 执行抽奖
        try {
            $draw_results = [];
            $draw_errors = [];
            $quantity = intval($order_blind_box['quantity']);
            
            for ($i = 0; $i < $quantity; $i++) {
                try {
                    $draw_result = BlindBoxModel::draw($uniacid, $order_blind_box['blind_box_id'], $customer_id, $order_blind_box['order_id']);
                    
                    if ($draw_result === false) {
                        $draw_errors[] = '第' . ($i + 1) . '次抽奖失败：暂无可用奖品';
                    } else {
                        // 处理奖品图片
                        if (!empty($draw_result['prize']['prize_image'])) {
                            $draw_result['prize']['prize_image'] = ImageModel::resize2($draw_result['prize']['prize_image'], 300, 300);
                        }
                        $draw_results[] = $draw_result;
                    }
                } catch (\Exception $e) {
                    $draw_errors[] = '第' . ($i + 1) . '次抽奖失败：' . $e->getMessage();
                }
            }
            
            // 更新盲盒订单记录状态为已抽奖
            if (!empty($draw_results)) {
                BlindBoxModel::mark_order_drawn($order_blind_box['id']);
                
                $res['draw_results'] = $draw_results;
                
                // 如果只抽了1个，直接返回单个结果（保持向后兼容）
                if ($quantity == 1 && count($draw_results) == 1) {
                    $res['draw_result'] = $draw_results[0];
                    $res['prize'] = $draw_results[0]['prize'];
                    $res['description'] = '恭喜您抽中：' . $draw_results[0]['prize']['prize_name'];
                } else {
                    $res['description'] = '抽奖成功！共抽中 ' . count($draw_results) . ' 个奖品';
                }
            }
            
            // 如果有抽奖错误，也记录下来
            if (!empty($draw_errors)) {
                $res['draw_errors'] = $draw_errors;
                if (empty($draw_results)) {
                    // 所有抽奖都失败了
                    $res['status'] = 1;
                    $res['description'] = '抽奖失败：' . implode('; ', $draw_errors);
                }
            }
            
        } catch (\Exception $e) {
            $res['status'] = 1;
            $res['description'] = '抽奖失败：' . $e->getMessage();
        }
        
        echo json_encode($res);
    }

    /**
     * 获取用户抽奖记录
     * @return void
     */
    public function my_records()
    {
        global $_W;
        
        $uniacid = $_W['uniacid'];
        
        $res = [
            'status' => 0
        ];
        
        // 检查登录状态
        if (empty($_W['customer'])) {
            $res['status'] = 1;
            $res['description'] = '请先登录';
            echo json_encode($res);
            return;
        }
        
        $customer_id = $_W['customer']['id'];
        $filter = [];
        
        if (!empty($_GET['blind_box_id'])) {
            $filter['blind_box_id'] = $_GET['blind_box_id'];
        }
        
        $records = BlindBoxModel::get_user_records($uniacid, $customer_id, $filter);
        
        // 处理图片
        foreach ($records as &$record) {
            if (!empty($record['prize_image'])) {
                $record['prize_image'] = ImageModel::resize2($record['prize_image'], 150, 150);
            }
            if (!empty($record['blind_box_image'])) {
                $record['blind_box_image'] = ImageModel::resize2($record['blind_box_image'], 100, 100);
            }
        }
        
        $res['records'] = $records;
        
        echo json_encode($res);
    }

    /**
     * 获取盲盒奖品展示（不含概率等敏感信息）
     * @return void
     */
    public function get_prizes()
    {
        global $_W;
        
        $uniacid = $_W['uniacid'];
        $blind_box_id = $_GET['blind_box_id'];
        
        $res = [
            'status' => 0
        ];
        
        $prizes = BlindBoxModel::get_prizes($uniacid, $blind_box_id);
        $display_prizes = [];
        
        foreach ($prizes as $prize) {
            if ($prize['status'] == 1) {
                // 只返回必要的展示信息，隐藏概率等敏感数据
                $display_prizes[] = [
                    'prize_name' => $prize['prize_name'],
                    'prize_image' => ImageModel::resize2($prize['prize_image'], 200, 200),
                    'prize_level' => $prize['prize_level'],
                    'prize_value' => $prize['prize_value']
                ];
            }
        }
        
        $res['prizes'] = $display_prizes;
        
        echo json_encode($res);
    }

    /**
     * 购买盲盒（生成订单）
     * @return void
     */
    public function buy()
    {
        global $_W, $_GPC;

        $uniacid = $_W['uniacid'];
        
        $res = [
            'status' => 0
        ];
        
        // 检查登录状态
        if (empty($_W['customer'])) {
            $res['status'] = 1;
            $res['description'] = '请先登录';
            echo json_encode($res);
            return;
        }
        
        $customer_id = $_W['customer']['id'];
        
        // 获取请求参数
        $post = [];
        if (isset($_GPC['__input'])) {
            $post = $_GPC['__input'];
        } else {
            $post = $_POST;
        }
        
        $blind_box_id = $_GPC['blind_box_id'] ?? null;
        $quantity = isset($_GPC['quantity']) ? intval($_GPC['quantity']) : 1;
        
        if (empty($blind_box_id)) {
            $res['status'] = 1;
            $res['description'] = '请选择盲盒';
            echo json_encode($res);
            return;
        }
        
        if ($quantity < 1) {
            $quantity = 1;
        }
        
        // 获取盲盒详情
        $blind_box = BlindBoxModel::detail($uniacid, $blind_box_id);
        
        if (empty($blind_box) || $blind_box['status'] != 1) {
            $res['status'] = 1;
            $res['description'] = '盲盒不存在或已下架';
            echo json_encode($res);
            return;
        }
        
        // 检查时间范围
        $now = date('Y-m-d H:i:s');
        if (!empty($blind_box['start_time']) && $now < $blind_box['start_time']) {
            $res['status'] = 1;
            $res['description'] = '活动未开始';
            echo json_encode($res);
            return;
        }
        
        if (!empty($blind_box['end_time']) && $now > $blind_box['end_time']) {
            $res['status'] = 1;
            $res['description'] = '活动已结束';
            echo json_encode($res);
            return;
        }
        
        // 检查库存
        if ($blind_box['stock'] > 0 && ($blind_box['sold'] + $quantity) > $blind_box['stock']) {
            $res['status'] = 1;
            $res['description'] = '库存不足';
            echo json_encode($res);
            return;
        }
        
        // 检查用户购买限制
        $limit_check = BlindBoxModel::check_user_limit($uniacid, $blind_box_id, $customer_id);
        if (!empty($blind_box['limit_per_user']) && 
            ($limit_check['bought_count'] + $quantity) > $blind_box['limit_per_user']) {
            $res['status'] = 1;
            $res['description'] = '超过购买上限（' . $limit_check['limit'] . '次）';
            echo json_encode($res);
            return;
        }
        
        // 获取配送方式和地址信息
        $shipping_method = $_GPC['shipping_method'] ?? 'package';
        
        // 准备订单数据
        $order_data = [];
        $order_data['customer_id'] = $customer_id;
        $order_data['order_no'] = 'BB' . $customer_id . date("YmdHis") . rand(1000, 9999);
        $order_data['payment_method'] = $_GPC['payment_method'] ?? 'wechat';
        $order_data['is_payed'] = 0;
        $order_data['status'] = 'pending';
        $order_data['message'] = $_GPC['message'] ?? '';
        $order_data['shipping_method'] = $shipping_method;
        
        // 处理地址信息
        if ($shipping_method == 'package') {
            // 快递配送
            if (empty($_GPC['address'])) {
                $res['status'] = 1;
                $res['description'] = '请填写收货地址';
                echo json_encode($res);
                return;
            }
            
            $address = json_decode($_GPC['address'], true);
            if (!is_array($address)) {
                $res['status'] = 1;
                $res['description'] = '地址信息格式错误';
                echo json_encode($res);
                return;
            }
            
            $order_data['address_name'] = $address['name'] ?? '';
            $order_data['address_phone'] = $address['telephone'] ?? '';
            $order_data['address_province'] = $address['province_name'] ?? '';
            $order_data['address_city'] = $address['city_name'] ?? '';
            $order_data['address_area'] = $address['area_name'] ?? '';
            $order_data['address_detail'] = $address['detail_address'] ?? '';
        } elseif ($shipping_method == 'pickup') {
            // 自提
            if (empty($_GPC['pickup_person']) || empty($_GPC['pickup_phone'])) {
                $res['status'] = 1;
                $res['description'] = '请填写自提人信息';
                echo json_encode($res);
                return;
            }
            
            if (empty($_GPC['pickup'])) {
                $res['status'] = 1;
                $res['description'] = '请选择自提点';
                echo json_encode($res);
                return;
            }
            $order_data['address_name'] = $_GPC['pickup_person'] ;
            $order_data['address_phone'] = $_GPC['pickup_phone'];
            if( is_string($_GPC['pickup'])){
                $order_data['pickup'] = json_decode($_GPC['pickup'], true);
            }else{
                $order_data['pickup'] = $_GPC['pickup'];
            }

            
            $order_data['address_province'] = '';
            $order_data['address_city'] = '';
            $order_data['address_area'] = '';
            $order_data['address_detail'] = '';
        }
        
        // 计算订单金额
        $unit_price = floatval($blind_box['price']);
        $goods_total = $unit_price * $quantity;
        
        // 构建商品信息（盲盒作为特殊商品）
        $order_data['goods'] = [
            $blind_box_id => [
                'goods_id' => $blind_box_id,
                'name' => $blind_box['name'] . '（盲盒）',
                'goods_name' => $blind_box['name'] . '（盲盒）',
                'goods_option' => '',
                'goods_num' => $quantity,
                'price' => $unit_price,
                'goods_price' => $unit_price,
                'total_price' => $goods_total,
                'goods_total' => $goods_total,
            ]
        ];
        
        // 构建订单总计信息
        $order_data['total'] = [
            'goods' => [
                'name' => '商品总额',
                'price' => round($goods_total, 2)
            ],
            'shipping' => [
                'name' => '运费',
                'price' => 0
            ],
            'total' => [
                'name' => '订单总额',
                'price' => round($goods_total, 2)
            ]
        ];
        
        try {
            // 调用OrderModel创建订单
            $order_id = OrderModel::create2($order_data);
            
            if (empty($order_id)) {
                $res['status'] = 1;
                $res['description'] = '订单创建失败';
                echo json_encode($res);
                return;
            }
            
            // 关联盲盒订单信息
            BlindBoxModel::link_order($uniacid, $blind_box_id, $order_id, $quantity);
            
            $res['order_id'] = $order_id;
            $res['order_no'] = $order_data['order_no'];
            $res['description'] = '订单创建成功';
            
            // 如果订单金额为0，自动完成支付
            if ($order_data['total']['total']['price'] == 0) {
                $order_status = $shipping_method == 'package' ? 'processing' : 'shipping';
                OrderModel::order_pay($order_id, $order_status, $order_data['payment_method']);
                $res['paid'] = true;
            }
            
            // 移除了执行抽奖逻辑的部分，用户需要主动调用draw接口进行抽奖
            
        } catch (\Exception $e) {
            $res['status'] = 1;
            $res['description'] = '订单创建失败：' . $e->getMessage();
        }
        
        echo json_encode($res);
    }

    /**
     * 获取盲盒订单详情（前台用户）
     * @return void
     */
    public function order_detail()
    {
        global $_W, $_GPC;
        
        $uniacid = $_W['uniacid'];
        
        $res = [
            'status' => 0
        ];
        
        // 检查登录状态
        if (empty($_W['customer'])) {
            $res['status'] = 1;
            $res['description'] = '请先登录';
            echo json_encode($res);
            return;
        }
        
        $customer_id = $_W['customer']['id'];
        $order_id = $_GPC['order_id'] ?? 0;
        
        if (empty($order_id)) {
            $res['status'] = 1;
            $res['description'] = '请提供订单ID';
            echo json_encode($res);
            return;
        }
        
        try {
            // 获取订单详情（验证订单归属）
            $order_detail = BlindBoxModel::get_order_detail($uniacid, $order_id, $customer_id);
            
            if (empty($order_detail)) {
                $res['status'] = 1;
                $res['description'] = '订单不存在或无权限访问';
                echo json_encode($res);
                return;
            }
            
            // 处理图片
            if (!empty($order_detail['blind_box_image'])) {
                $order_detail['blind_box_image'] = ImageModel::resize2($order_detail['blind_box_image'], 300, 300);
            }
            
            // 处理抽奖记录中的图片
            if (!empty($order_detail['draw_records'])) {
                foreach ($order_detail['draw_records'] as &$record) {
                    if (!empty($record['prize_image'])) {
                        $record['prize_image'] = ImageModel::resize2($record['prize_image'], 200, 200);
                    }
                }
            }
            
            // 格式化订单状态
            $order_detail['status_text'] = self::getOrderStatusText($order_detail['status']);
            $order_detail['payment_method_text'] = self::getPaymentMethodText($order_detail['payment_method']);
            $order_detail['shipping_method_text'] = $order_detail['shipping_method'] == 'package' ? '快递配送' : '到店自提';
            $order_detail['is_payed_text'] = $order_detail['is_payed'] ? '已支付' : '未支付';
            $order_detail['is_drawn_text'] = $order_detail['is_drawn'] ? '已抽奖' : '未抽奖';
            
            // 计算抽奖延迟时间
            if ($order_detail['draw_time'] && $order_detail['create_time']) {
                $order_detail['draw_delay_seconds'] = strtotime($order_detail['draw_time']) - strtotime($order_detail['create_time']);
            }
            
            $res['order'] = $order_detail;
            
        } catch (\Exception $e) {
            $res['status'] = 1;
            $res['description'] = '获取订单详情失败：' . $e->getMessage();
        }
        
        echo json_encode($res);
    }

    /**
     * 获取盲盒订单列表（前台用户）
     * @return void
     */
    public function order_list()
    {
        global $_W, $_GPC;
        
        $uniacid = $_W['uniacid'];
        
        $res = [
            'status' => 0
        ];
        
        // 检查登录状态
        if (empty($_W['customer'])) {
            $res['status'] = 1;
            $res['description'] = '请先登录';
            echo json_encode($res);
            return;
        }
        
        $customer_id = $_W['customer']['id'];
        
        // 分页参数
        $page = isset($_GPC['page']) ? intval($_GPC['page']) : 1;
        $page_size = isset($_GPC['page_size']) ? intval($_GPC['page_size']) : 10;
        $offset = ($page - 1) * $page_size;
        
        try {
            // 获取用户盲盒订单列表
            $sql = "SELECT 
                        o.*,
                        obb.blind_box_id,
                        obb.quantity as blind_box_quantity,
                        obb.is_drawn,
                        obb.draw_time,
                        bb.name as blind_box_name,
                        bb.image as blind_box_image,
                        bb.price as blind_box_price
                    FROM sh_order o
                    LEFT JOIN sh_order_blind_box obb ON o.id = obb.order_id
                    LEFT JOIN sh_blind_box bb ON obb.blind_box_id = bb.id
                    WHERE o.customer_id = " . intval($customer_id) . "
                    AND o.uniacid = " . intval($uniacid) . "
                    AND obb.blind_box_id IS NOT NULL
                    ORDER BY o.create_time DESC
                    LIMIT " . $offset . "," . $page_size;
            
            $orders = Db::query($sql);
            
            // 处理订单数据
            foreach ($orders as &$order) {
                // 处理图片
                if (!empty($order['blind_box_image'])) {
                    $order['blind_box_image'] = ImageModel::resize2($order['blind_box_image'], 150, 150);
                }
                
                // 格式化状态文本
                $order['status_text'] = self::getOrderStatusText($order['status']);
                $order['payment_method_text'] = self::getPaymentMethodText($order['payment_method']);
                $order['shipping_method_text'] = $order['shipping_method'] == 'package' ? '快递配送' : '到店自提';
                $order['is_payed_text'] = $order['is_payed'] ? '已支付' : '未支付';
                $order['is_drawn_text'] = $order['is_drawn'] ? '已抽奖' : '未抽奖';
            }
            
            // 获取总数量
            $count_sql = "SELECT COUNT(*) as count
                        FROM sh_order o
                        LEFT JOIN sh_order_blind_box obb ON o.id = obb.order_id
                        WHERE o.customer_id = " . intval($customer_id) . "
                        AND o.uniacid = " . intval($uniacid) . "
                        AND obb.blind_box_id IS NOT NULL";
            
            $count_result = Db::query($count_sql);
            $total = $count_result[0]['count'];
            
            $res['orders'] = $orders;
            $res['total'] = $total;
            $res['page'] = $page;
            $res['page_size'] = $page_size;
            $res['description'] = '获取成功';
            
        } catch (\Exception $e) {
            $res['status'] = 1;
            $res['description'] = '获取订单列表失败：' . $e->getMessage();
        }
        
        echo json_encode($res);
    }

    /**
     * 获取订单状态文本
     * @param string $status
     * @return string
     */
    private static function getOrderStatusText($status)
    {
        $statusMap = [
            'pending' => '待支付',
            'processing' => '处理中',
            'shipping' => '配送中',
            'completed' => '已完成',
            'canceled' => '已取消'
        ];
        
        return $statusMap[$status] ?? '未知';
    }

    /**
     * 获取支付方式文本
     * @param string $method
     * @return string
     */
    private static function getPaymentMethodText($method)
    {
        $methodMap = [
            'wechat' => '微信支付',
            'alipay' => '支付宝',
            'cash' => '现金支付',
            'balance' => '余额支付'
        ];
        
        return $methodMap[$method] ?? $method;
    }
}
